<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Get Selected Text</title>
</head>

<body>
<input onmouseup="getSelectedText();" type="text" value="some words ,hahhs" />
<textarea onmouseup="getSelectedText();">some words,hahhs</textarea>
<div style="border:1px solid black;margin:5px 0px;" onmouseup="getSelectedText();">
some words hahs
</div>
<div id="result" style="border:1px solid red;color:red;width:200px;"></div>

<script>
function $(id){return document.getElementById(id)}
function getSelectedText(){
	if(window.getSelection){
		var aElem = document.activeElement
		if(aElem&&(aElem.tagName.toLowerCase()=='textarea'||aElem.tagName.toLowerCase()=='input')){
			var s = aElem.selectionStart,e = aElem.selectionEnd;
			$('result').innerHTML = aElem.value.substring(s,e);
		}else{
			$('result').innerHTML = window.getSelection().toString();
		}
	}else{
		var range = document.selection.createRange();
		$('result').innerHTML = range.text;
	}
}
</script>
</body>
</html>
